import { roleGet, userLogin } from "../../api/user";

export const LOGIN_START = "LOGIN_START"; //开始登录
export const LOGIN_SUCCESS = "LOGIN_SUCCESS"; //登录成功
export const LOGIN_FAIL = "LOGIN_FAIL"; //登录失败

export const start = () => {
  return {
    type: LOGIN_START,
  };
};

export const success = (userInfo) => {
  return {
    type: LOGIN_SUCCESS,
    userInfo,
  };
};

export const fail = () => {
  return {
    type: LOGIN_FAIL,
  };
};

// 异步action
export const loginAsyncAction = (account, history) => {
  return (dispatch) => {
    dispatch(start()); //开始登录
    userLogin(account)
      .then(async (res) => {
        let role = await roleGet(res.data.roleId); //使用角色id获取角色权限
        console.log("当前用户的角色权限", role.data);
        dispatch(success({ ...res.data, ...role.data })); //登录成功
        history.push("/");
      })
      .catch((err) => {
        dispatch(fail()); //登录失败
      });
  };
};
